import logging

import os
import sys
import platform
from typing import Optional

from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon

from meet_record.app import MeetingRecordApp
from meet_record.api import FlaskClient
from voice_assistant.config_manager import config_manager
from voice_assistant.event_system import event_system, Events
from voice_assistant.plugin_system import PluginManager, ensure_plugin_directory
from voice_assistant.ui.floating_window import FloatingMicWindow
from voice_assistant.ui.tray_icon import create_qt_tray_icon
from voice_assistant.voice.microphone import VoiceRecorder
from voice_assistant.ws.ws_client import run_async_websocket
from voice_assistant.com_utils import run_in_thread, check_and_install_dependencies

logger = logging.getLogger("VoiceAssistantApp")

class VoiceAssistantApp:
    """语音助手应用程序核心类
    
    整合所有组件，管理应用程序生命周期
    """
    
    def __init__(self):
        self.qt_app: Optional[QApplication] = None
        self.floating_window: Optional[FloatingMicWindow] = None
        self.tray_icon = None
        self.recorder: Optional[VoiceRecorder] = None
        self.plugin_manager: Optional[PluginManager] = None
        
        # 初始化配置
        config_manager.load()
        
        # 实例化Flask客户端
        self.flask_client = FlaskClient()
    
    def initialize(self) -> bool:
        """初始化应用程序
        Returns:
            bool: 初始化是否成功
        """
        logger.info("正在初始化语音助手应用程序...")
        
        try:
            # 创建Qt应用程序
            self.qt_app = QApplication(sys.argv)
            self.qt_app.setQuitOnLastWindowClosed(False)#子程序退出后不影响主程序
            
            # 设置DPI感知
            if platform.system() == "Windows":
                try:
                    from ctypes import windll
                    windll.shcore.SetProcessDpiAwareness(1)
                    logger.info("已设置DPI感知")
                except Exception as e:
                    logger.error(f"DPI感知设置失败: {str(e)}")
            
            icon_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 
                        "assets", "icon", "aipc.ico")
            if os.path.exists(icon_path):
                self.qt_app.setWindowIcon(QIcon(icon_path))
            else:
                logger.error("无法找到应用程序图标文件，无法设置窗口图标")
            
            # 创建悬浮窗口
            self.floating_window = FloatingMicWindow()
            self.floating_window.show()
            
            # 创建系统托盘图标
            self.tray_icon = create_qt_tray_icon(self)  # 传递VoiceAssistantApp实例而不是QApplication
            if self.tray_icon:
                logger.info("已创建系统托盘图标")
                self.tray_icon.show()
            
            # 确保插件目录存在
            ensure_plugin_directory()
            
            # 初始化插件管理器
            self.plugin_manager = PluginManager(self)
            self.plugin_manager.load_plugins()
            
            # 子程序
            self.meet_app = MeetingRecordApp()
            
            # 启动录音
            self.recorder = VoiceRecorder()
            self.recorder.start()
            
            # 启动WebSocket连接
            def delayed_start():
                import time
                time.sleep(1)  # 等待1秒，让界面先显示
                run_async_websocket()
            
            run_in_thread(delayed_start)
            
            # 订阅事件
            event_system.subscribe(Events.CONFIG_CHANGED, self.on_config_changed)
            # 发布启动事件
            event_system.publish(Events.STARTUP, {"app": self})
            
            logger.info("语音助手客户端已启动，等待唤醒...")
            return True
            
        except Exception as e:
            logger.error(f"初始化应用程序失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return False
    
    def on_config_changed(self, data: dict) -> None:
        logger.info("重新加载配置...")
        config_manager.load()
    
    def run(self) -> int:
        """运行应用程序
        Returns:
            int: 退出代码
        """
        if not self.qt_app:
            logger.error("应用程序未初始化")
            return 1
        
        return self.qt_app.exec_()
    
    def shutdown(self) -> None:
        """安全关闭应用程序"""
        logger.info("正在关闭应用程序...")
        
        # 发布关闭事件
        event_system.publish(Events.SHUTDOWN, {"app": self})
        
        # 关闭插件
        if self.plugin_manager:
            self.plugin_manager.shutdown_all()
        
        # 停止录音
        if self.recorder:
            self.recorder.stop()
        
        # 关闭子程序
        if hasattr(self, "meet_app") and self.meet_app:
            self.meet_app.stop()
        
        # 清理事件系统
        event_system.clear_all()
        
        # 退出Qt应用程序
        if self.qt_app:
            self.qt_app.quit()

#==================================================
    
def main():
    """应用程序主函数"""
    
    # 检查并安装依赖项
    if not check_and_install_dependencies():
        logger.error("依赖项安装失败，程序将退出")
        sys.exit(1)
    
    try:
        # 创建并初始化应用程序
        app = VoiceAssistantApp()
        if not app.initialize():
            logger.error("应用程序初始化失败")
            sys.exit(1)
        
        # 运行应用程序
        exit_code = app.run()
        
        # 关闭应用程序
        app.shutdown()
        
        sys.exit(exit_code)
        
    except KeyboardInterrupt:
        logger.info("程序已被用户中断")
        sys.exit(0)
    except Exception as e:
        logger.error(f"致命错误: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        sys.exit(1)